import { GenericEnvStore } from "@/modules/dev-env/store/generic-env-store.ts";
import type { LocalVersionItem, ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { NodejsNpmMirror } from "@/modules/dev-env/nodejs/nodejs-mirror.ts";
import type { UnzipCompleteArgs } from "@common/archives-file-types.ts";
import type { EnvTableAction, EnvVariableConfig } from "@/modules/dev-env/store/types.ts";
import { execInTerminal } from "@/util/system-utils2.ts";
import { defineAsyncComponent } from "vue";
import { EnvTree } from "@/modules/dev-env/common/tree.ts";

export class NodejsEnvStore extends GenericEnvStore<NodejsEnvStore> {
  constructor() {
    super("nodejs");
    this.icon = "icon-nodejs";
    this.tableActions = this._tableActions();
    this.settingExtraComponent = defineAsyncComponent(() => import("./nodejs-settings.vue"));
  }

  protected _tableActions(): EnvTableAction[] {
    return [
      {
        key: "node_repl",
        name: "Node.js REPL",
        icon: "icon-nodejs",
        onClick: v => execInTerminal("node", { cwd: v.installPath }),
      },
    ];
  }

  protected getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    const version = path.basename(versionDir);
    return Promise.resolve({ version, installPath: versionDir });
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [new NodejsNpmMirror()];
  }

  getEnvVariables0(): EnvVariableConfig[] {
    return [
      {
        name: "PATH",
        getValue: () => path.join(this.installDir, EnvTree.currentVersionDir),
        settable: false,
        readonly: true,
        copyName: false,
      },
    ];
  }

  async afterUnzipComplete(e: UnzipCompleteArgs, version: ToolInstallVersionItem): Promise<void> {
    // 文件解压目录 /path/to/<输出目录>/<压缩文件名>
    const unzipedVersionDir = path.resolve(e.fileDir, path.basename(e.sourceFile, path.extname(e.sourceFile)));
    // 安装目录 /path/to/<输出目录>/v<版本号>
    const installDir = path.resolve(e.fileDir, version.version);
    if (__DEV__) console.log("[nodejs-version-item] unzip success", unzipedVersionDir);
    // 重命名解压目录
    await native.fs.rename(unzipedVersionDir, installDir);
    if (__DEV__) console.log("[nodejs-version-item] rename succuss", unzipedVersionDir, ">", installDir);
  }
}
